package com.wyhello.tube4.dao.impl;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.wyhello.tube4.dao.TubeRecordsDAO;
import com.wyhello.tube4.pojo.Tube;

public class TubeRecordsDAOImpl  implements TubeRecordsDAO{
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	/**
	 * 管信息的录入
	 * @param tube 要录入的管信息
	 * @return 返回是否录入成功
	 */
	@Override
	public boolean saveTube(Tube tube) {
		Session session = sessionFactory.getCurrentSession();
		int i = 1;
		try{
			session.save(tube);
		}catch(Exception e){
			i=0;
		}
		if(i==1){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 对管信息进行批量删除
	 * @param ids 要删除的id
	 * @return 返回删除的条数
	 */
	@Override
	public int deleteTube(String ids) {
		Session session  =  sessionFactory.getCurrentSession();
		String sql = "delete from tube where id in "+ids;
		int i = session.createSQLQuery(sql).executeUpdate();
		return i;
	}
	/**
	 * 查询所有的管信息
	 * @return 返回所有管信息
	 */
	@Override
	public List<Tube> queryTube() {
		Session session  =  sessionFactory.getCurrentSession();
		String hql = "from Tube";
		List<Tube> list = session.createQuery(hql).list();
		return list;
	}
	/**
	 * 根据id查询管信息
	 * @param id 要查询的id
	 * @return 为ID的管信息
	 */
	@Override
	public Tube getTubeById(int id) {
		Session session  =  sessionFactory.getCurrentSession();
		Tube tube = (Tube) session.get(Tube.class, Integer.valueOf(id));
		return tube;
	}
	/**
	 * 对管信息进行修改
	 * @param tube 修改后的信息
	 * @return 修改是否成功
	 */
	@Override
	public boolean updateTube(Tube tube) {
		Session session  =  sessionFactory.getCurrentSession();
		try{
			session.update(tube);
		}catch(Exception e){
			return false;
		}
		return true;
	}
	@Override
	public void deleteTOj(Tube tube) {
		Session session  =  sessionFactory.getCurrentSession();
		session.delete(tube);
	}
	/**
	 * 根据管排Id查询管的数量
	 * @param resideId
	 * @return
	 */
	@Override
	public int queryCountTubeByResideId(int resideId) {
		Session session  =  sessionFactory.getCurrentSession();
		//System.out.println(session.createSQLQuery("SELECT COUNT(*) FROM tube WHERE resideId = "+resideId).list().get(0));
		List<BigInteger> l = session.createSQLQuery("SELECT COUNT(*) FROM tube WHERE resideId = "+resideId).list();
		return l.get(0).intValue();
	}
}
